using System.Reflection;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using SqlSugar;

var builder = WebApplication.CreateBuilder(args);


builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();


#region 注入数据库 SqlSugar ORM

builder.Services.AddSingleton(options =>
{
    return new SqlSugarScope(new List<ConnectionConfig>
        {
            new()
            {
                DbType = DbType.MySql,
                ConnectionString = builder.Configuration["ConnectString"],
                IsAutoCloseConnection = true
            }
        },
        db =>
        {
            //单例参数配置，所有上下文生效       
            db.Aop.OnLogExecuting = (sql, pars) =>
            {
                Console.WriteLine(sql); //输出sql
            };
        }
    );
});

#endregion

#region 初始化Autofac 注入程序集

builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
var hostBuilder = builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{
    var assembly = Assembly.Load("SqlsugarDemo");
    builder.RegisterAssemblyTypes(assembly).Where(a => a.Name.EndsWith("Repository")).AsSelf();
});

#endregion

#region 初始化AutoMapper 自动映射

var serviceAssembly = Assembly.Load("SqlsugarDemo");
builder.Services.AddAutoMapper(serviceAssembly);

#endregion

var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.UseAuthorization();
app.MapControllers();
app.Run();